#include "types.h"
#include "stat.h"
#include "user.h"

int
str_len(char *str)
{
    int i=0;

    while(*str!='\0'){
        str++;
        i++;
    }

    return i;
}

int
is_all_num(char* str)
{
    int i=0;

    char c=*str;
    while(c!='\0'){
        if(c>'9' || c<'0'){
            return 1;
        }

        str++;
        c=*str;                
    }

    return i;
}

int
hund(int j)
{
    int ret=1;
    for(int i=1;i<=j;i++)
    {
        ret=ret*10;
    }

    return ret;
}


int
str_to_num(char* str)
{
    int i=0;
    int j=0;

    char c=*str;
    int len=str_len(str);
    while(c!='\0'){
        
        j=j+(c-'0')*hund(len-i-1);

        str++;
        c=*str;     
        i++;           
    }

    return j;
}

int 
doubleX(int a)
{
    return a*2;
}

int
main(int argc, char *argv[])
{
  //int i=0;

  if(argc < 2){
    printf(2, "Usage: cal num...\n");
    exit();
  }

  if(argc == 2){
    char* str_num=argv[1];
    int is_num = is_all_num(str_num);
    if(is_num==1){
        printf(2, "Error:argv is not all number...\n");
        exit();
    }

    printf(2,"length of str is %d\n",str_len(str_num));
    //printf(2,"num of str is %d\n",str_to_num(str_num));
    printf(2,"double of argv is %d\n",doubleX(str_to_num(str_num)));  
  }

  if(argc ==3){
    int a=atoi(argv[1]);
    int b=atoi(argv[2]);

    printf(2,"sum  of %d + %d = %d\n",a,b,a+b);  
  }

  if(argc>3){
    for(int i=1;i<argc;i++)
    {
        if(is_all_num(argv[i])==1)
        {
            printf(2,"argv %d is not number\n",i);
            break;
        }
    }

    int sum=0;
    for(int i=1;i<argc;i++)
    {
        int a=atoi(argv[i]);
        sum+=a;
    }

    printf(1,"argc is greater then 3;sum is %d \n",sum);
  }

  exit();
}




